import React, { Component } from 'react';
import { Text, View, TouchableOpacity, Alert, ScrollView, BackHandler, Platform, KeyboardAvoidingView } from "react-native";
import { style } from '../../../../theme/style';
import { orderBlockStyle } from '../_common/style';
import { AddLongBtn } from '../_components/AddLongBtn.js';
import { TitleView } from '../_components/TitleView.js';
import { SelectComponent } from '../_components/SelectComponent';
import { Common } from '../../../../component/common/Common.js';
import { SpaceBetween } from '../_components/SpaceBetween.js';
import { PageStatusIndex } from '../../../../component/page-status/PageStatusIndex';
import OrderAPIService from '../_common/OrderAPIService';
import OrderCreactService from '../_common/service';
import { CURRENCY } from '../../../../utils/helper';
import ToastUtil from '../../../../utils/toast';
import MethodUtil from '../../../../utils/MethodUtil';
import HTTP from '../../../../utils/http';
import { API, API_GENERATE } from '../../../../config/api';
import { RadiusGroupCpt } from '../../../order-new/create/_components/RadiusGroupCpt';
import Dictionary from '../../../../utils/dictionary';
/*
*orderType  销售->S   采购->P
*periodType 长约->L   普通->S
*tCode   现货->S   长约->L  远期->F   代理->A   E->远期执行  C->背靠背
*/
let pageData;
export class QHOrderGoodsInfoPage extends Component {
	static navigationOptions = {
		header: ({ navigation }) => {
			let { state: { routes } } = navigation;
			Navigation_routers = routes;//全局的路由
		}
	}
	requesting;
	constructor(props) {
		super(props);
		this.jumpPage = OrderCreactService.jump.bind(this);
		this.resetPage = OrderCreactService.reset.bind(this);
		pageData = {};
		this.pushIndex = -1;
		this.state = {
			status: 'data',
			totalAmount: ''
		}

		this.goodsData = {}
		this.showData = {};
		this.customerFunds = 0;
		this.QHStore = '';
	}

	async	componentWillMount() {
		this.initData();
		if (Platform.OS === 'android') {
			BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid);
		}
	}

	componentWillUnmount() {
		if (Platform.OS === 'android') {
			BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid);
		}
	}

	initData = () => {
		let { titleName, tCode, orderId, longOrderId, orderType, companyId, deliveryType, companyName, baseDateSettleName, baseDateSettle, currency } = this.props.navigation.state.params || {};
		pageData = { titleName, tCode, orderId, longOrderId, orderType, companyId, deliveryType, companyName, baseDateSettleName, baseDateSettle, currency };
		let { label, text } = CURRENCY.getUnit(currency);
		this.unitSymbol = label;
		this.unit = text;
		// if (deliveryType === 'T' || deliveryType === 'U') {
		// 	this.getQHStore();
		// }
		this.getGoodsData();  // 商品数据初始化
		this.getCustomerFunds();//获取客户资金
		this.initDictionary();//液气化数据字典
	}

	// getQHStore = async () => {
	// 	responseData = await HTTP.POST(API_GENERATE(API.CONST), {});
	// 	if (responseData) {
	// 		this.QHStore = responseData.WMS_QZ_WAREHOUSE_NAME;
	// 	}
	// }

	//数据字典-液气化数据字典
	async initDictionary() {
		let sourcePrice = await Dictionary.get('EC_OD_SOURCE_DATA');
		console.log('sourcePrice---', sourcePrice)
		this.setState({
			sourcePrice: sourcePrice || [],
		});
	}

	//获取客户资金
	getCustomerFunds = async () => {
		let responseData = await OrderAPIService.getCustomerFunds({ companyId: pageData.companyId, currency: pageData.currency });
		this.customerFunds = responseData.value;
	}

	onBackAndroid = () => {
		if (Navigation_routers[Navigation_routers.length - 1].routeName == 'OrderGoodsInfoPage') {
			Alert.alert(
				'提示',
				'您是要放弃创建当前成交报告吗？',
				[
					{
						text: '放弃', onPress: () => {
							this.props.navigation.goBack()
						}
					},
					{ text: '取消', onPress: () => { } },
				],
				{ cancelable: false }
			)
			return true
		}
	}

	//获取商品-数据
	async getGoodsData() {
		this.setState({ status: 'loading' });
		let responseData = await OrderAPIService.getGoodsList({ queryType: 'ORDER_ITEM_LIST', orderId: pageData.orderId }) || [];
		this.goodsData = responseData[0] || {};
		this.initGoodsData();
		this.setState({
			status: 'data'
		})
	}

	initGoodsData = async (data) => {
		let { logisticsPrice } = this.props.navigation.state.params || {};
		if (data) {
			this.goodsData.goodsId = data.goodsId;
			this.goodsData.goodsName = data.goodsName;
			this.goodsData.logisticsPrice = logisticsPrice || 0;
			// this.goodsData.endAddressList = data.endAddressList;//目的地
			// this.goodsData.deliveryAddressList = data.deliveryAddressList;//仓库地址
			this.goodsData.priceFormlaId = data.priceFormlaId;//	结算价
			this.goodsData.priceFormulaId = data.priceFormulaId;
			this.goodsData.tempPriceFormulaId = data.tempPriceFormulaId;
			this.goodsData.udPrice = data.udPrice;
			this.goodsData.priceFormulaDesc = data.priceFormulaDesc;
			this.goodsData.quantity = '';
			this.goodsData.priceType = data.priceType;
			this.goodsData.longItemId = data.longItemId || '';
			this.goodsData.sourceData = data.sourceData;// 涞源数据初始化
			this.goodsData.qhPriceChangeFlag = data.qhPriceChangeFlag;// 涞源数据初始化
		}
		if (this.goodsData.goodsId) {
			this.executeProductInfo();
			this.planInit();
			await this._getOrderOtherPrice();
			this.getGoodsTotalAmount();
		}
	}


	// 单价 =  现货价+运费+-升贴水-客户优惠
	//订单总价 = (现货价+运费+-升贴水-客户优惠)*数量

	//获取商品总价
	getGoodsTotalAmount = () => {  // 升贴水-> udPrice   运价(+) ->  现货提报价 ->     客户优惠-> 
		let { quantity, udPrice, rebatePrice, suggestedPrice, qhPriceChangeFlag, sourceData } = this.goodsData;
		let { logisticsPrice } = this.props.navigation.state.params || {};
		let params = {};
		params.rebatePrice = "-" + rebatePrice;
		params.suggestedPrice = suggestedPrice;
		params.udPrice = udPrice;
		params.logisticsPrice = logisticsPrice;
		// 液化石油气
		console.log('this.goodsData', this.goodsData)

		let price = 0;
		if (qhPriceChangeFlag == '1' && sourceData == 'CHEMIC') {
			price = MethodUtil.countObj.add(this.goodsData.price, logisticsPrice);
			//
		} else {
			//this.goodsData.price = this.multiAdd(params);
			price = this.multiAdd(params);
		}
		let totalAmount = MethodUtil.countObj.multiply(price, Number.parseFloat(quantity || '0'));
		this.setState({ totalAmount }, () => {
			this.goodsData.price = price;
			console.log('价格', this.goodsData)
		})
	}

	multiAdd = (params) => {
		let sumData = 0;
		for (const value in params) {
			sumData = MethodUtil.countObj.add(Number.parseFloat(params[value] || '0'), sumData)
		}
		return sumData;
	}
	// 初始化-计划量
	async	planInit() {
		let responseData = await HTTP.POST(API_GENERATE(API.ORDER_GOODS_PLAN), { goodsId: this.goodsData.goodsId, planType: pageData.orderType, isUnite: 1 })
		if (responseData) {
			let { planMonthLimitQuantity } = responseData;
			this.showData.planMonthLimitQuantity = planMonthLimitQuantity;
			this.setState({
				ls: true
			})
		}
	}

	// 初始化-长约框架-商品总量/商品剩余
	async executeProductInfo() {
		let responseData = await OrderAPIService.executeProductInfo({ goodsId: this.goodsData.goodsId, longOrderId: pageData.longOrderId, longItemId: this.goodsData.longItemId })
		if (responseData) {
			let { longOrderPlan, longOrderLimit, longOrderMax } = responseData
			this.showData.longOrderPlan = longOrderPlan;
			this.showData.longOrderLimit = longOrderLimit;
			this.showData.longOrderMax = longOrderMax;
			this.setState({
				ls: true
			})
		}
	}

	_getOrderOtherPrice = async () => {
		console.log('现货价-开始')
		let { qhPriceChangeFlag, sourceData } = this.goodsData || {};
		if (sourceData) {
			if (sourceData == 'CHEMIC') return
		} else {
			if (qhPriceChangeFlag == '1') return
		}
		let subData = {
			orderId: pageData.orderId,
			orderItemInfo: {
				orderId: pageData.orderId,
				itemId: this.goodsData.itemId,
				goodsId: this.goodsData.goodsId,
				longOrderId: pageData.orderId
			}
		}
		let respData = await OrderAPIService.getOrderOtherPrice(subData) || {};
		this.goodsData.rebatePrice = respData.rebatePrice || 0;
		this.goodsData.suggestedPrice = respData.suggestedPrice || 0;
		this.setState({ refresh: true })
		console.log('现货价-结束')
	}
	//获取商品列表
	gotoGoodsList = () => {
		let { logisticsPrice } = this.props.navigation.state.params || {};
		let params = {
			pushIndex: this.pushIndex,
			orderId: pageData.longOrderId,
			type: 'EXECUTE',
			logisticsPrice: logisticsPrice
		};
		this.jumpPage('ProductSelectPage', params, this.goodsListCb);
	}
	//商品回显
	goodsListCb = (data, index) => {
		console.log('商品回显', data)
		if (data) {
			this.pushIndex = index;
			this.initGoodsData(data);
			this.setState({ refresh: true }, () => {
				console.log('this.goodsData-999', this.goodsData)
			});
		}
	}

	// 回填地址
	addressCallBack = (data) => {
		if (!data.length) return;
		this.goodsData.endAddressList = data
		this.setState({
			ls: true
		})
	}

	//验证授信额度
	checkCredit = async () => {
		let saveData = await OrderAPIService.orderCreditCheck({ orderId: pageData.orderId }, {
			rejectError: true, //是否将错误数据以reject的方式返回
			handerError: false //统一出错处理 通过toast提示
		});
		if (!saveData) {
			return
		}
		if (!saveData.isReject) {
			return true
		} else {
			//授信额度不通过
			let companyRole = '';
			if (saveData.code == '11' || saveData.code == '13') {
				companyRole = '企业';
				this.showAlert(companyRole);
			} else {
				ToastUtil.showError(saveData.msg || '请求出错啦！')
			}
			return false
		}
	}

	showAlert = (companyRole) => {
		Alert.alert('提示', `${companyRole}循环授信申请金额不足，可前往申请企业授信`, [
			{
				text: '确定',
			}, {
				text: '前往申请',
				onPress: () => {
					this.props.navigation.navigate('CreditFormPage', { companyId: pageData.companyId, orderType: pageData.orderType })
				}
			}
		])
	}

	submitGoods = async () => {
		let { logisticsPrice } = this.props.navigation.state.params || {};
		if (!this.goodsData.goodsId) {
			ToastUtil.showWarning('请选择商品');
			return false
		}
		// if (pageData.deliveryType === 'S' && !this.goodsData.endAddressList) {
		// 	ToastUtil.showWarning('请输入目的地');
		// 	return false
		// }

		if (!this.goodsData.quantity) {
			ToastUtil.showWarning('请输入数量');
			return false
		}
		if (this.goodsData.quantity <= 0) {
			ToastUtil.showWarning('数量必须大于0');
			return false
		}
		if (this.goodsData.qhPriceChangeFlag == '1' && !this.goodsData.sourceData) {
			ToastUtil.showWarning('请选择价格来源');
			return false
		}

		if (!this.goodsData.suggestedPrice || this.goodsData.suggestedPrice <= 0) {
			if (this.goodsData.sourceData != 'CHEMIC') {
				ToastUtil.showWarning('该商品暂无现货价');
				return false
			}
		}
		// if (this.goodsData.qhPriceChangeFlag == '1' && this.goodsData.sourceData == 'CHEMIC' && this.goodsData.price <= 0) {
		// 	ToastUtil.showWarning('现货价必须大于0');
		// 	return false
		// }
		if (Number.parseFloat(this.goodsData.quantity || 0) > Number.parseFloat(this.showData.longOrderLimit || 0)) {
			ToastUtil.showWarning(`商品数量必须<${this.showData.longOrderLimit}`);
			return false
		}
		this.goodsData.logisticsPrice = logisticsPrice || 0;
		let subData = {
			orderId: pageData.orderId,
			orderItemList: []
		};
		subData.orderItemList.push(this.goodsData);
		console.log('subData', subData)
		let saveData = await OrderAPIService.goodsAdd(subData, { rejectError: true, handerError: false })
		if (saveData.isReject) {
			ToastUtil.showError(saveData.msg || '保存失败');
			return false
		};
		return true;
	}

	//下一步/提交/保存
	async	nextStep(str, opType) {
		if (this.requesting) return;
		this.requesting = true;
		if (!await this.submitGoods()) {
			this.requesting = false
			return;
		}

		let orderInfo = {
			orderId: pageData.orderId,
			isQhXhXsBiz: 'Y'
		}
		//暂定价需要更新结算基准日期
		if (pageData.priceType == '2') orderInfo.baseDateSettle = pageData.baseDateSettle;
		//验证授信
		if (!await this.checkCredit()) return;
		let sendData = {
			submitStep: str,
			orderInfo
		}
		this.setState({
			status: 'loading'
		})
		sendData.logisticsPrice = this.props.navigation.state.params.logisticsPrice || '0';
		let saveData = await OrderAPIService.orderAdd(sendData);
		this.setState({
			status: 'data'
		})

		if (saveData) {
			setTimeout(() => {
				this.requesting = false;
			}, 1000)

			//闭口/代理  提交或保存
			let msg = '已保存到草稿';
			// status 0,1,2,3 已通过 审批中 已驳回 草稿
			let status = 'RPT_DRAFT';
			if (opType == 'submit') {
				msg = '提交成功';
			}
			if (saveData.status) {
				status = saveData.status
			}
			ToastUtil.showSuccess(msg).then(() => {
				this.resetPage(pageData.orderType, pageData.tCode, status);
			})

		} else {
			this.requesting = false;
		}
	}
	//数量输入
	_quantityFn = (str) => {
		this.goodsData.quantity = str;
		this.getGoodsTotalAmount()
	}

	_headCloes = () => {
		this.props.navigation.goBack()
	}

	_radiusItemFn = (itemData) => {
		console.log('itemData', itemData)
		this.goodsData.price = '';
		this.goodsData.sourceData = itemData;
		if (itemData == 'CHEMIC') {
			this.goodsData.priceType = 1; // 一口价
		} else {
			this.goodsData.priceType = 2;  // 暂定价
			this._getOrderOtherPrice();
		}
		this.getGoodsTotalAmount()
		//this.setState({ ls: true })
	}

	//价格 泉化 液化气
	_getPrice = (str) => {
		this.goodsData.price = str;
		this.getGoodsTotalAmount()
	}

	render() {
		let { goodsName, quantity, suggestedPrice, rebatePrice, priceFormulaDesc, goodsId, udPrice, qhPriceChangeFlag, sourceData, priceType, price } = this.goodsData || {};
		let { status, totalAmount, sourcePrice } = this.state;
		let { titleName, baseDateSettleName } = pageData || {};
		let { logisticsPrice } = this.props.navigation.state.params || {};
		// let endAddressValue = endAddressList ? endAddressList[0] ? endAddressList[0].addressName ? endAddressList[0].addressName : endAddressList[0].detailAddress : '' : '';
		return (
			<KeyboardAvoidingView style={orderBlockStyle.container} behavior={Platform.OS === 'ios' ? 'padding' : null} keyboardVerticalOffset={20}>
				<ScrollView showsVerticalScrollIndicator={false} keyboardShouldPersistTaps={'handled'}>
					<Common type="headCloes" callBack={this._headCloes} />
					<TitleView title={titleName} />
					<View style={orderBlockStyle.paddingB100}>
						<View style={orderBlockStyle.formBox}>
							<SelectComponent name="商品名称" value={goodsName} callBack={this.gotoGoodsList} />
							{goodsId ? <View>
								<SelectComponent keyboardType='numeric' name="数量" type="input" rightText={'吨'} value={quantity} inputFn={this._quantityFn} />
								{
									qhPriceChangeFlag == '1' ? <RadiusGroupCpt data={{
										title: '价格来源',
										listData: sourcePrice,
										selectedKey: sourceData,
										_radiusItemFn: this._radiusItemFn,
										id: 'sourceData'
									}} /> : null
								}

								{
									qhPriceChangeFlag == '1' && sourceData == 'CHEMIC' ? <SelectComponent keyboardType='numeric' name="现货价" type="input" rightText={this.unit + '/吨'} value={price} inputFn={this._getPrice} /> : null
								}

								<Text style={orderBlockStyle.info}>长约总量:{this.showData.longOrderPlan},长约剩余量:{this.showData.longOrderLimit},计划剩余量:{this.showData.planMonthLimitQuantity}</Text>
								{/* 我司配送和供应商配送 显示运费,目的地可修改 */}
								{/* {pageData.deliveryType === 'P' || pageData.deliveryType === 'S' ? <SelectComponent name="目的地" callBack={this.gotoAddressList} value={endAddressValue} /> : null} */}
								{/* {pageData.deliveryType === 'T' || pageData.deliveryType === 'U' ? <SelectComponent name="出库地" editable={false} type='input' value={this.QHStore} /> : null} */}
								{
									qhPriceChangeFlag == '1' && sourceData == 'CHEMIC' ? null : (
										<View>
											<Text style={orderBlockStyle.label}>结算价公式</Text>
											<Text style={orderBlockStyle.value}>{priceFormulaDesc}</Text>
										</View>
									)
								}


								{priceType && priceType == '2' ? <SpaceBetween fontLeft={{ title: '结算基准日期', style: orderBlockStyle.paddingT20 }} fontRight={{ title: baseDateSettleName, style: orderBlockStyle.paddingT20 }} /> : null}
								<SpaceBetween fontLeft={{ title: '订单总价', style: { color: '#F66464' } }} fontRight={{ title: totalAmount ? `${this.unitSymbol}${totalAmount}` : '无' }} />
								<SpaceBetween fontLeft={{ title: '客户余额', style: { color: '#F66464' } }} fontRight={{ title: this.unitSymbol + this.customerFunds }} />
								{
									qhPriceChangeFlag == '1' && sourceData == 'CHEMIC' ?
										<SpaceBetween fontLeft={{ title: '现货价' }} fontRight={{ title: price ? `${this.unitSymbol}${price}${this.unit}/吨` : '无' }} />
										: <SpaceBetween fontLeft={{ title: '现货价' }} fontRight={{ title: suggestedPrice ? `${this.unitSymbol}${suggestedPrice}${this.unit}/吨` : '无' }} />
								}

								{
									qhPriceChangeFlag == '1' && sourceData == 'CHEMIC' ? null : (
										<View>
											<SpaceBetween fontLeft={{ title: '客户优惠幅度' }} fontRight={{ title: this.unitSymbol + (rebatePrice || '') + this.unit + '/吨' }} />
											<SpaceBetween fontLeft={{ title: '升贴水' }} fontRight={{ title: this.unitSymbol + udPrice + this.unit + '/吨' }} />
											{/* <SpaceBetween fontLeft={{ title: '运费单价' }} fontRight={{ title: this.unitSymbol + (logisticsPrice || '0') + this.unit + '/吨' }} /> */}
										</View>
									)
								}
								<SpaceBetween fontLeft={{ title: '运费单价' }} fontRight={{ title: this.unitSymbol + (logisticsPrice || '0') + this.unit + '/吨' }} />
							</View> : null}
						</View>
					</View>
				</ScrollView>
				<AddLongBtn callBack={() => { this.props.navigation.goBack() }} direction="left" text="上一步" bottom="20" colorBg={style.color.ceruleanUp} />
				<TouchableOpacity onPress={() => { this.nextStep('SAVE_ORDER_DRAFT', 'save') }} style={orderBlockStyle.saveBtnBox} >
					<Text style={orderBlockStyle.saveBtn}>保存</Text>
				</TouchableOpacity>
				<AddLongBtn callBack={() => { this.nextStep('ORDER_SUBMIT_AUDIT', 'submit') }} text="提交" direction="right" bottom="20" colorBg={style.color.cerulean} />
				{
					status != 'data' ? (<View style={orderBlockStyle.statusStyle}><PageStatusIndex status={status} /></View>) : null
				}
			</KeyboardAvoidingView >
		)
	}
}
